package com.sxhuayuan.parking.controller.agent;

import com.alibaba.fastjson.JSONObject;
import com.sxhuayuan.parking.compenent.Message;
import com.sxhuayuan.parking.compenent.Pageable;
import com.sxhuayuan.parking.compenent.web.RespMessage;
import com.sxhuayuan.parking.compenent.web.RespMessage.Status;
import com.sxhuayuan.parking.controller.BaseController;
import com.sxhuayuan.parking.entity.Agent;
import com.sxhuayuan.parking.entity.OemConfig;
import com.sxhuayuan.parking.exception.SessionTimeoutException;
import com.sxhuayuan.parking.service.AdminService;
import com.sxhuayuan.parking.service.AgentService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/** */
@RestController("agentAgentController")
@RequestMapping("/agent/agent")
public class AgentController extends BaseController {

	@Resource(name = "agentServiceImpl")
	AgentService service;

	@Resource(name = "adminServiceImpl")
	AdminService adminService;

	/** 删除用户 */
	@RequestMapping("/delete")
	public RespMessage deleteAgent(Long id) {
		if (Objects.isNull(id)) {
			return RespMessage.error(Status.VALID_ERR, Message.FORM_VALID_FAIL);
		}
		service.delete(id);
		return RespMessage.success();

	}

	/** 查询所有代理 */
	@RequestMapping("/list")
	public RespMessage pagelist(@RequestBody Pageable pageable) {
		Agent current = service.getCurrent();
		return RespMessage.builder().success().setDatas(service.findPage(pageable, current)).build();
	}

	/** 根据用户名和密码查询 */
	@RequestMapping("/getinfo")
	public RespMessage getCurrent() {
		Agent agent = service.getCurrent();
		if (agent == null) {
			throw new SessionTimeoutException();
		}
		JSONObject user = new JSONObject();
		user.put("username", agent.getUsername());
		user.put("type", "agent");
		user.put("name", agent.getName());

		List<String> auths = new ArrayList<>();
		agent.getRoles().forEach((v) -> auths.addAll(v.getAuthorities()));
		OemConfig oemConfig = agent.getOemConfig();
		if (oemConfig != null) {
			user.put("maxLogo", oemConfig.getMaxLogo());
			user.put("minLogo", oemConfig.getMinLogo());
			user.put("icon", oemConfig.getIcon());
			user.put("forShort", oemConfig.getForShort());
			user.put("fullname", oemConfig.getFullName());
			if (oemConfig.getOwnerId().equals(agent.getId())) {
				auths.add("agent:oemConfig");
			}
		}
		user.put("access", auths);
		return RespMessage.builder().success().setDatas(user).build();
	}

	/** 添加代理 */
	@RequestMapping("/save")
	public RespMessage save(@Validated @RequestBody Agent agent, HttpServletRequest request) {
		Agent current = service.getCurrent();

		if (current == null) {
			return RespMessage.error("登录失效，请重新登录");
		}
		if (current.getOemConfig() == null) {
			return RespMessage.error("代理oem未配置，请联系管理员");
		}
		if (agent.getWeixinRate() < current.getWeixinRate()) {
			return RespMessage.error("微信费率不能小于自己的代理费率");
		}
		if (agent.getAlipayRate() < current.getAlipayRate()) {
			return RespMessage.error("支付宝费率不能小于自己的代理费率");
		}
		if (service.usernameExists(agent.getUsername())) {
			return RespMessage.builder().validError().setErr(Message.FORM_UNIQUE_INVALID).build();
		}
		agent.setOemConfig(current.getOemConfig());
		agent.setLoginIp(request.getRemoteAddr());
		service.save(agent, service.getCurrent());
		return RespMessage.success();
	}

	/** 锁定 启用 */
	@RequestMapping("/enable")
	public RespMessage enable(Long id, Boolean value) {
		if (Objects.isNull(id) || Objects.isNull(value)) {
			return RespMessage.error(Status.VALID_ERR, Message.FORM_VALID_FAIL);
		}
		Agent agent = service.findOne(id);
		agent.setIsEnabled(value);
		service.update(agent);
		return RespMessage.success();
	}

	@RequestMapping(value = "/get", method = RequestMethod.GET)
	public RespMessage get(Long id) {
		Agent agent = service.findOne(id);
		if (agent == null || !service.isPermission(agent)) {
			return RespMessage.noPermissionError();
		}
		return RespMessage.builder().success().setDatas(agent).build();
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public RespMessage update(@Validated @RequestBody Agent agent) {
		Agent current = service.getCurrent();
		if (current == null) {
			return RespMessage.error("登录失效，请重新登录");
		}
		if (agent.getWeixinRate() < current.getWeixinRate()) {
			return RespMessage.error("微信费率不能小于自己的代理费率");
		}
		if (agent.getAlipayRate() < current.getAlipayRate()) {
			return RespMessage.error("支付宝费率不能小于自己的代理费率");
		}
		service.update(agent);
		return RespMessage.success();
	}

	/* 查询全部子代理 */
	@GetMapping(value = "/getchildrenlist")
	public RespMessage getChildrenList() {
		List<Agent> all = service.getChildrenList(service.getCurrent());
		return RespMessage.builder().success().setDatas(all).build();
	}

	/** 代理修改自己的密码 */
	@PostMapping("/changepassword")
	public RespMessage changePassword(@RequestParam String password, @RequestParam String updatePassword) {
		Agent current = service.getCurrent();
		if (current == null) {
			return RespMessage.error("登录失效，请重新登录");
		}
		String s = DigestUtils.md5Hex(password);

		if (!s.equals(current.getPassword())) {
			return RespMessage.error("原密码输入错误");
		}

		String pattern = "^[^\\s&\"<>]+$";
		if (!(updatePassword.length() >= 4 && updatePassword.length() <= 64 && updatePassword.matches(pattern))) {
			return RespMessage.error("新密码格式不正确");
		}
		current.setPassword(DigestUtils.md5Hex(updatePassword));
		service.update(current);
		return RespMessage.success();
	}

	/** 获取当前登录代理详情 */
	@GetMapping("/info")
	public RespMessage info() {
		Agent current = service.getCurrent();
		if (current == null) {
			return invalidToken();
		}
		return successResp(current);
	}
}
